<template>
  <div class="home-wrapper">
    <project-menu :detail="projectDetail"
                  :pid="projectId"></project-menu>
    <div class="properson_le">
      <div class="filters-wrapper">
        <div class="title total_title"
             style="justify-content: start;">项目账户
          <div class="form-wrapper fl"
               style="width: 300px;margin-bottom: 0;">
            <el-input placeholder="请输入内容"
                      size="small"
                      v-model="account_search"
                      class="input-with-select"
                      @keyup.enter="loadAccountData({page: 1})">
              <el-button slot="append"
                         @click="loadAccountData({page: 1})"
                         icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </div>
        <el-table :data="account"
                  border
                  :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                  style="width: 100%;margin-top: 10px"
                  ref="multipleTable"
                  @selection-change="handleSelectionChange">
          <template slot="empty"
                    style="text-align: left">
            <el-empty description="暂无数据" />
          </template>
          <el-table-column type="selection"
                           width="55"
                           align="center">
          </el-table-column>
          <el-table-column prop="account"
                           label="账户名称"
                           align="center">
          </el-table-column>
          <el-table-column prop="optimizer"
                           label="优化师"
                           align="center">
          </el-table-column>
          <el-table-column prop="operate"
                           width="300"
                           align="center">
            <template slot-scope="scope">
              <el-button v-if="projectDetail.status == 1"
                         size="mini"
                         type="primary"
                         @click="configOptimizerClick(scope.row)">分配</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex"
                justify="end"
                style="margin-top: 20px;">
          <el-button style="margin-right: 15px;"
                     type="primary"
                     plain
                     v-if="projectDetail.status == 1"
                     size="small"
                     @click="batConfig">批量分配
          </el-button>
          <el-pagination background
                         layout="prev, pager, next"
                         :current-page.sync="curPage"
                         :total="total"
                         :page-size="pageSize"
                         @current-change="handleCurrentChange('account',$event)">
          </el-pagination>
        </el-row>

      </div>
    </div>
    <div class="properson_ri">
      <div class="filters-wrapper">
        <div class="title total_title">项目成员</div>
        <el-table :data="users"
                  border
                  :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                  style="width: 100%;margin-top: 10px"
                  ref="multipleTable"
                  @selection-change="handleSelectionChange">
          <el-table-column prop="name"
                           align="center">
            <template slot="header"
                      slot-scope="scope">
              <el-row type="flex"
                      justify="space-between">
                项目人员<el-button v-if="projectDetail.status == 1"
                           size="mini"
                           type="primary"
                           @click="addUserClick(scope.row)"
                           v-loading.fullscreen.lock="fullscreenLoading">新增人员
                </el-button>
              </el-row>
            </template>
            <template slot-scope="scope">
              {{scope.row.name}}
              <el-button v-if="projectDetail.status == 1"
                         size="mini"
                         type="text"
                         style="color: #F56C6C;margin-left: 6px;"
                         @click="removeUserClick(scope.row)"
                         icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分割线 -->
    <el-dialog title="分配优化师"
               :visible.sync="allotperson"
               :close-on-click-modal="false"
               center>
      <div class="allotperson">
        <el-radio-group v-model="configUserId">
          <el-radio v-for="item in users"
                    :key="item.id"
                    :label="item.id">{{item.name}}</el-radio>
        </el-radio-group>
      </div>
      <el-row type="flex"
              align="middle"
              justify="center">
        <el-button size="small"
                   @click="allotperson = false">取 消</el-button>
        <el-button size="small"
                   type="primary"
                   @click="configOptimizerSaveClick()">确 定</el-button>
      </el-row>
    </el-dialog>

    <el-dialog title="项目人员管理"
               :visible.sync="addprojectperson"
               :close-on-click-modal="false"
               center
               @close="cancelPost">
      <div class="form-wrapper"
           style="width: 200px;margin: 0 0 15px 0;padding-left: 0;">
        <el-input placeholder="请输入内容"
                  size="small"
                  v-model="person_search"
                  class="input-with-select"
                  @input="searchCont()"
                  @keyup.enter="searchCont()">
          <!-- el-button slot="append" @click="searchCont()" icon="el-icon-search"></el-button -->
        </el-input>
      </div>
      <div class="allotperson">
        <el-checkbox-group v-model="addpersondata">
          <el-checkbox class="allpersonList"
                       v-for="item in allUsers"
                       :key="item.id"
                       :label="item.id">
            {{item.name}}</el-checkbox>
        </el-checkbox-group>
      </div>
      <el-row type="flex"
              align="middle"
              justify="center">
        <el-button size="small"
                   @click="cancelPost()">取 消</el-button>
        <el-button size="small"
                   type="primary"
                   @click="addUserPostClick">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<style>
.properson_le {
  width: calc(100% - 315px);
  float: left;
  margin-right: 15px;
}

.properson_ri {
  width: 300px;
  float: left;
}

.allotperson {
  margin-bottom: 20px;
  max-height: 200px;
  overflow-y: auto;
}

.allotperson .el-radio {
  width: 80px;
  margin-bottom: 10px;
}
</style>
<script>
import {
  pageParams
} from '@/settings'
export default {
  data () {
    return {
      fullscreenLoading: false,
      projectId: 0,
      projectDetail: {},
      account: [],
      total: 0,
      curPage: 1,
      pageSize: pageParams.pageSize,
      users: [],
      configAccount: [],
      allotperson: false,
      configUserId: 0,
      addprojectperson: false,
      addpersondata: [],
      allUsers: [],
      multipleSelection: [],
      account_search: '',
      person_search: '',
      person_searchlist: []
    }
  },
  created () {
    this.projectId = this.$router.currentRoute.params.id
  },
  mounted () {
    this.loadData()
  },
  methods: {
    loadData () {
      this.$axios.get('/project/detail', {
        projectid: this.projectId
      })
        .then(e => {
          this.projectDetail = e.data
        })
      //加载业务数据
      this.loadAccountData({})
      this.loadUserData({})
    },
    loadAccountData (param) {
      param['number'] = this.pageSize
      param['projectid'] = this.projectId
      param['keyword'] = this.account_search
      if (!param['page']) {
        param['page'] = 1
      }
      this.curPage = param['page']
      this.loading = true
      this.$axios.get('/project/account', param)
        .then(e => {
          this.loading = false
          this.account = e.data.items
          this.total = e.data.total
        }).catch(() => {
          this.loading = false
        })
    },
    loadUserData (param) {
      param['projectid'] = this.projectId
      this.$axios.get('/project/user', param)
        .then(e => {
          this.users = e.data.items
        })
    },
    handleCurrentChange (t, val) {
      // this.curPageAccount = val
      this.loadAccountData({
        page: val
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    batConfig () {
      if (this.multipleSelection.length <= 0) {
        this.$message.error('没有选中项目')
        return
      }
      this.configAccount = this.multipleSelection
      this.allotperson = true
    },
    configOptimizerClick (item) {
      // console.log(item)
      this.configAccount = [item]
      if (this.configAccount.length > 0) {
        this.configUserId = this.configAccount[0]['optimizerid']
      }
      this.allotperson = true
    },
    configOptimizerSaveClick () {
      if (this.configUserId <= 0) {
        this.$message.error('没有选中项目')
        return
      }
      this.allotperson = false
      let accountIds = []
      this.configAccount.forEach(e => {
        accountIds.push(e.id)
      })
      this.$axios.post('/project/account/save', {
        accountid: accountIds,
        optimizerid: this.configUserId
      })
        .then((e) => {
          // this.configAccount['optimizerid'] = this.configUserId
          this.configAccount.forEach(e => {
            e.optimizerid = this.configUserId
          })
          this.$message({
            message: e.msg ? e.msg : '保存成功',
            type: 'success'
          })
          this.loadAccountData({ page: this.curPage })
        })
    },
    removeUserClick (item) {
      this.$confirm('此操作将移除[' + item.name + '], 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post('/project/account/remove', {
          projectid: this.projectId,
          id_user: item.id
        })
          .then(() => {
            let idx = this.users.findIndex((ele) => {
              return ele.id == item.id
            })
            if (idx > -1) {
              this.users.splice(idx, 1)
            }
            this.$message({
              type: 'success',
              message: '移除成功!'
            })
          })

      }).catch(() => { })
    },
    addUserClick () {
      this.fullscreenLoading = true
      this.$axios.get('/user/list').then((e) => {
        console.log(e)
        this.allUsers = e.data
        this.allUsers = this.allUsers.filter((ele) => {
          let i = this.users.findIndex((u) => {
            return u.id == ele.id
          })
          return i == -1
        })
        this.addprojectperson = true
        this.fullscreenLoading = false
        this.person_searchlist = this.allUsers
      }).catch(() => {
        this.fullscreenLoading = false
      })
    },
    cancelPost () {
      this.addprojectperson = false
      this.addpersondata = []
    },
    addUserPostClick () {
      this.addprojectperson = false
      this.fullscreenLoading = true
      let personArr = []
      this.addpersondata.forEach(p => {
        let person = this.allUsers.find((ele) => {
          return ele.id == p
        })
        if (person) {
          personArr.push(person)
        }
      });

      this.$axios.post('/project/user/list', {
        projectid: this.projectId,
        id_user: JSON.stringify(this.addpersondata)
      })
        .then((e) => {
          personArr.forEach(p => {
            this.users.push(p)
          })
          this.fullscreenLoading = false
          this.$message({
            message: e.msg ? e.msg : '保存成功',
            type: 'success'
          })
          // this.loadUserData({})
        })
    },
    searchCont () {
      if (this.person_search.length == 0 || this.person_search.split(" ").join("").length == 0) {
        this.allUsers = this.person_searchlist
      } else {
        this.allUsers = this.person_searchlist.filter(item => {
          return item.name.includes(this.person_search)
        })
      }
      // this.person_search = ''
    }
  }
}
</script>
